// pages/room/room.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: null,
    roomStatus: 'free',   //free, full, searching, playing4中状态
    voice: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.goods_id = options.goods_id;
    this.sku_id = options.sku_id;
    //获取商品信息
    this.getGoodsInfo();
    //播放背景音乐
    this.playBgMusic();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //清理所有定时器和背景音乐
    this.clearAllTimer();
    this.destroyBgMusic();
  },

  /**
   * 清楚所有定时器
   */
  clearAllTimer: function () {
    if (this.searchInterval) {
      clearInterval(this.searchInterval);
    }
    if (this.waitInterval) {
      clearInterval(this.waitInterval);
    }
    if (this.searchingTimeout) {
      clearTimeout(this.searchingTimeout);
    }
    if (this.checkVideoStatusTimeout) {
      clearTimeout(this.checkVideoStatusTimeout);
    }
  },

  /**
   * 获取商品信息
   */
  getGoodsInfo: function () {
    app.Ajax({
      url: '/api/index.php?app=goods&act=goods_sku_info',
      data: {
        goods_id: this.goods_id,
        sku_id: this.sku_id
      },
      success: (res) => {
        this.setData({
          goods: res
        })
      },
      fail: (err) => {
        this.setData({
          message: err,
        })
        setTimeout(() => {
          wx.navigateBack({
            delta: 2
          })
        }, 2000);
      }
    })
  },

  /**
   * 玩游戏
   */
  playGame: function () {
    this.setData({
      searchingTime: '00:00',
      roomStatus: 'searching',
      rtmp_address: null,
    })
    //寻找空闲房间
    this.searchFreeRoomCost();
    this.delaySarchFreeRoom();
  },

  /**
   * 计算寻找房间消耗时间
   */
  searchFreeRoomCost: function () {
    this.searchingTime = 0;
    if (this.searchInterval) {
      clearInterval(this.searchInterval);
    }
    this.searchInterval = setInterval(() => {
      this.searchingTime++;
      //寻找房间最多30秒
      if (this.searchingTime > 30) {
        this.roomFullWait();
        return;
      }

      var time;
      if (this.searchingTime < 10) {
        time = '00:0' + this.searchingTime
      } else {
        time = '00:' + this.searchingTime
      }
      this.setData({
        searchingTime: time
      })
    }, 1000);
  },

  /**
   * 延迟搜索空闲房间
   */
  delaySarchFreeRoom: function (delayTime) {
    delayTime = delayTime || 1000;
    if (this.searchingTimeout) {
      clearTimeout(this.searchingTimeout);
    }
    this.searchingTimeout = setTimeout(() => {
      if (this.data.roomStatus == 'searching') {
        this.searchFreeRoom();
      }
    }, delayTime);
  },

  /**
   * 寻找空闲房间
   */
  searchFreeRoom: function () {
    app.Ajax({
      url: '/api/index.php?app=game&act=get_free_device_count',
      success: (res) => {
        if (res.free_device_count > 0) {
          console.log('已找到空闲机器')
          this.room_id = res.room_id;
          this.setData({
            rtmp_address: res.rtmp_address,
          })
          //检查视频加载状态
          this.checkVideoLoadStatus(() => {
            console.log('机器画面拉流失败，寻找新的空闲机器')
            this.delaySarchFreeRoom();
          });
        } else {
          console.log('未找到空闲机器')
          this.delaySarchFreeRoom(3000);
        }
      },
      fail: (err, code) => {
        this.gameover();
        if (code == 10001) {
          this.setData({
            message: '房间爆满，请稍后再玩'
          })
          return;
        }
        this.setData({
          message: err
        })
      }
    })
  },

  /**
   * 房间爆满，等待3秒可以再次开始游戏
   */
  roomFullWait: function () {
    this.clearAllTimer();
    this.setData({
      rtmp_address: null,
      roomStatus: 'full'
    })
    this.waitTime = 0;
    this.waitInterval = setInterval(() => {
      this.waitTime++;
      if (this.waitTime > 2) {
        clearInterval(this.waitInterval);
        this.setData({
          roomStatus: 'free'
        })
      }
    }, 1000);
  },

  /**
   * 检查视频加载状态，如果5s内没有加载成功则算失败
   */
  checkVideoLoadStatus: function (cb) {
    this.checkVideoStatusTimeout = setTimeout(() => {
      this.setData({
        rtmp_address: null,
      })
      typeof cb == 'function' && cb();
    }, 5000);
  },

  /**
   * 视频加载成功
   */
  videoLoadSuccess: function (e, failCb) {
    //取消视频状态检查
    if (this.checkVideoStatusTimeout) {
      clearTimeout(this.checkVideoStatusTimeout);
    }
    app.Ajax({
      method: 'POST',
      url: '/api/index.php?app=game&act=store',
      data: {
        goods_id: this.goods_id,
        sku_id: this.sku_id,
        room_id: this.room_id,
      },
      success: (res) => {
        //开始游戏
        this.gamestart(res);
      },
      fail: (err, code) => {
        if (code == 10024) {
          //设备被占用
          if (failCb && typeof failCb == 'function') {
            failCb();
          } else {
            this.setData({
              rtmp_address: null,
            })
            this.delaySarchFreeRoom();
          }
        } else {
          //游戏结束
          this.gameover();
          //报错信息以及处理结果
          if (code == 10023) {
            this.setData({
              message: '您的星星数量不足'
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              })
            }, 2000)
          } else if (code == 10025) {
            this.setData({
              message: '上局游戏非法退出，请30s后面再试'
            })
          } else {
            console.log('开始游戏失败，错误码:' + code);
            this.setData({
              message: err
            })
            setTimeout(() => {
              wx.navigateBack({
                delta: 1
              })
            }, 2000)
          }
        }
      }
    })
  },

  /**
   * 游戏开始
   */
  gamestart: function (gameInfo) {
    //取消寻房时间计数
    if (this.searchInterval) {
      clearInterval(this.searchInterval);
    }
    this.setData({
      gameInfo: gameInfo,
      roomStatus: 'playing',
    })
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#fff1b8',
    });
    //更新用户星星
    app.getUserInfo();
  },

  /**
   * 游戏结束
   */
  gameover: function () {
    this.clearAllTimer();
    this.setData({
      roomStatus: 'free',
      rtmp_address: null
    });
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#fffae6',
    });
  },

  /**
   * 再玩一次
   */
  gamePlayAgain: function (e) {
    console.log('gamePlayAgain');
    //默认视频已加载完成
    this.videoLoadSuccess(null, () => {
      this.gameover();
      this.playGame();
    });
  },

  /**
   * 背景音乐
   */
  playBgMusic: function () {
    var index = parseInt(Math.random() * 5 + 1);
    var audioSrc = "http://testwangoula3.artqiyi.com/wangoula_backend_h5/static/bgm/00" + index + ".mp3";

    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.autoplay = true;
    this.innerAudioContext.src = audioSrc;
    this.innerAudioContext.onPlay(() => {
      this.setData({
        voice: true
      })
      console.log('开始播放');
    })
    this.innerAudioContext.onPause(() => {
      this.setData({
        voice: false
      })
      console.log('暂停播放');
    })
    this.innerAudioContext.onEnded(() => {
      var index = parseInt(Math.random() * 5 + 1);
      var audioSrc = "http://testwangoula3.artqiyi.com/wangoula_backend_h5/static/bgm/00" + index + ".mp3";
      this.innerAudioContext.src = audioSrc;
      this.innerAudioContext.play();
    })
    this.innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    this.innerAudioContext.play();
  },

  /**
   * 
   */
  destroyBgMusic: function () {
    this.innerAudioContext.offPlay();
    this.innerAudioContext.offPause();
    this.innerAudioContext.offEnded();
    this.innerAudioContext.offError();
    this.innerAudioContext.destroy();
  },

  /**
   * 声音开关
   */
  voiceSwitchChange: function () {
    if (this.data.voice) {
      this.innerAudioContext.pause();
    } else {
      this.innerAudioContext.play();
    }
  },
})